package com.example.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.bookstore.common.BaseContext;
import com.example.bookstore.common.PageResult;
import com.example.bookstore.common.Result;
import com.example.bookstore.dto.QueryCartParamsDto;
import com.example.bookstore.entity.Book;
import com.example.bookstore.entity.Cart;
import com.example.bookstore.entity.Orders;
import com.example.bookstore.mapper.BookMapper;
import com.example.bookstore.mapper.CartMapper;
import com.example.bookstore.service.CartService;
import jdk.nashorn.internal.ir.IfNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {
    @Autowired
    CartMapper cartMapper;
    @Autowired
    BookMapper bookMapper;
    @Override
    public Result<String> addCart(Cart cart) {
        int bookId = cart.getBookId();
        int userId = cart.getUserId();
        Date date=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(date);
        cart.setAddTime(format);
        LambdaQueryWrapper<Cart> qw=new LambdaQueryWrapper<>();
        qw.eq(Cart::getBookId,bookId).eq(Cart::getUserId,userId);
        List<Cart> carts = cartMapper.selectList(qw);
        if (carts.size()>0){
            return Result.error("购物车已存在该书籍");
        }
        int insert = cartMapper.insert(cart);
        if (insert>0){
            return Result.success("加入购物车成功");
        }
        return Result.error("加入购物车失败");
    }

    @Override
    public PageResult<Cart> selectCart(int pageSize, int currentPage, QueryCartParamsDto params) {
        Page<Cart> page=new Page<>(currentPage,pageSize);
        LambdaQueryWrapper<Cart> qw=new LambdaQueryWrapper<>();
        long userId = BaseContext.getCurrentId();
        qw.eq(Cart::getUserId,userId);
        if (!StringUtils.isEmpty(params.getBookName())){
            List<Integer> ids=bookMapper.selectLikBookName("%"+params.getBookName()+"%");
            if (ids.size()==0){
                qw.in(Cart::getBookId,-1);//模糊查询不到数据
            }else {
                qw.in(Cart::getBookId,ids);
            }
        }
        qw.ge(!StringUtils.isEmpty(params.getStartDate()),Cart::getAddTime,params.getStartDate());
        qw.le(!StringUtils.isEmpty(params.getEndDate()),Cart::getAddTime,params.getEndDate());
        qw.orderByDesc(Cart::getAddTime);
        Page<Cart> pageResult = cartMapper.selectPage(page, qw);
        List<Cart> records = pageResult.getRecords();
        records.forEach(item->{
            Book book = bookMapper.selectById(item.getBookId());
            item.setBookImg(book.getBookImg());
            item.setBookName(book.getBookName());
            item.setBookPrice(book.getPrice());
            item.setInventory(book.getInventory());
            item.setStatus(book.getStatus());
        });
        long total = pageResult.getTotal();
        PageResult<Cart> result=new PageResult<>(records,total,currentPage,pageSize);
        return result;
    }

    @Override
    public Result deleteCarts(List<Integer> ids) {
        for (int i = 0; i < ids.size(); i++) {
            long id = ids.get(i);
            int del = cartMapper.deleteById(id);
            if (del < 1) {
                return Result.error("删除失败");
            }
        }
        return Result.success("删除成功");
    }

    @Override
    public Result updateQuantity(int quantity, int id) {
        LambdaQueryWrapper<Cart> qw=new LambdaQueryWrapper<>();
        qw.eq(Cart::getId,id);
        Cart cart = cartMapper.selectOne(qw);
        cart.setQuantity(quantity);
        cartMapper.updateById(cart);
        return Result.success("更新数量成功");
    }
}
